package com.example.webserver.controller;


import com.example.webserver.entity.Result;
import com.example.webserver.entity.User;
import com.example.webserver.service.IUserservice;
import com.example.webserver.utils.JWTUtil;
import com.example.webserver.utils.ThreadLocalUtil;
import org.apache.ibatis.annotations.Mapper;
import org.hibernate.validator.constraints.URL;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.util.StringUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@RestController
@Validated
@RequestMapping("user")
public class Usercontroller {
    @Autowired
    IUserservice userservice;
    @PostMapping("register")
    public Result register(@Valid String username,@Valid String password){
        userservice.register(username,password);
        return Result.success();
    }
    @PostMapping("login")
    public Result<String> login(@Valid String username,@Valid String password){
         String token=userservice.login(username,password);
         return Result.success(token);
    }

    @PutMapping("update")
    public Result update(@RequestBody @Valid User user){
        userservice.update(user);
        return Result.success();
    }

    @GetMapping("userInfo")
    public Result<User> userinfo(){
        User user=userservice.getuserInfo();
        return Result.success(user);
    }
    @PatchMapping("updateAvatar")
    public Result updateAvatar(@URL @RequestParam String url){
        userservice.updateAvatar(url);
        return Result.success();
    }

    @PatchMapping("updatePsw")
    public Result updatePsw(@RequestBody Map<String,String>params,@RequestHeader("Authorization") String token){
        String oldpsw=params.get("old_psw");
        String newpsw=params.get("new_psw");
        String repsw=params.get("re_psw");

        if(!StringUtils.hasLength(oldpsw)||!StringUtils.hasLength(newpsw)||!StringUtils.hasLength(repsw)){
            return Result.error("参数错误");
        }
        if(!repsw.equals(newpsw)){
            return Result.error("密码确认失败");
        }
        userservice.updatePsw(oldpsw,newpsw);
        return Result.success();
    }
}
